//
//  ZMNetWorkingRequest.m
//  ZMUnderFrameWorkDemo
//
//  Created by chenzm on 2020/4/29.
//  Copyright © 2020 MAC. All rights reserved.
//

#import "ZMNetWorkingRequest.h"


@interface ZMNetWorkingRequest ()

@end

@implementation ZMNetWorkingRequest

+ (instancetype)share {
    
    return [[self alloc] init];
}

- (instancetype)init {
    
    self = [super init];
    if (self) {
        self.manager = [AFHTTPSessionManager manager];
        self.manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
        self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应
        self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];//请求
        [self.manager.requestSerializer setStringEncoding:NSUTF8StringEncoding];//java参数传值
        // 设置超时时间
        [self.manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        self.manager.requestSerializer.timeoutInterval = 8;
    }
    return self;
}


- (NSURLSessionDataTask *)zm_postUrl:(NSString *)url params:(NSDictionary *)params success:(void (^)(NSDictionary * response))success failure:(void (^)(NSError * error))failure{
    
    [self setTemporaryHeaderRequest];

    ZMLog(@"\n🌺UserId:\n%@\nTOKEN:\n%@\n🌺🌺URL:\n%@\n🌺🌺🌺Param:\n%@",
    [UserInfoM getUserInfo].userId,
    [UserInfoM getUserInfo].token,
    ZYZH_API(url),
    params.mj_JSONString);
    NSURLSessionDataTask *task = [self.manager POST:ZYZH_API(url) parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            NSDictionary *dic = [ZMNetWorkingRequest jsonToDic:responseObject];
            ZMLog(@"\n🌸URL:\n%@\n🌸🌸Response:\n%@",ZYZH_API(url),dic.mj_JSONString);
            success(dic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            failure(error);
        }
    }];
    return task;
}

- (NSURLSessionDataTask *)zm_getUrl:(NSString *)url params:(NSDictionary *)params success:(void (^)(NSDictionary * response))success failure:(void (^)(NSError * error))failure{
    [self setTemporaryHeaderRequest];
    ZMLog(@"\n🌺UserId:\n%@\nTOKEN:\n%@\n🌺🌺URL:\n%@\n🌺🌺🌺Param:\n%@",
          [UserInfoM getUserInfo].userId,
          [UserInfoM getUserInfo].token,
          ZYZH_API(url),
          params.mj_JSONString);
    
    NSURLSessionDataTask *task = [self.manager GET:ZYZH_API(url) parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            NSDictionary *dic = [ZMNetWorkingRequest jsonToDic:responseObject];
            ZMLog(@"\n🌸URL:\n%@\n🌸🌸Response:\n%@",ZYZH_API(url),dic.mj_JSONString);
            success(dic);
        }else{
            NSLog(@"🤪🤪啊!啊!啊!返回空数据！！🤪🤪");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            failure(error);
        }
    }];
    return task;
}

/// 图片上传
/*fileType:文件类型 0、图片 1、视频 */
- (NSURLSessionDataTask *)zm_uploadFileUrl:(NSString *)url
                fileType:(NSInteger)fileType
                filesArr:(NSArray *)filesArr
                  params:(NSDictionary *)params
                 maxByte:(NSInteger)maxByte// 最大上传质量 单位kB 0、默认原件上传
                 success:(void (^)(NSDictionary * response))success
                 failure:(void (^)(NSError * error))failure{
    
    [self setTemporaryHeaderRequest];
    ZMLog(@"\n🌺UserId:\n%@\nTOKEN:\n%@\n🌺🌺URL:\n%@\n🌺🌺🌺Param:\n%@",
          [UserInfoM getUserInfo].userId,
          [UserInfoM getUserInfo].token,
          ZYZH_API(url),
          params.mj_JSONString);
    
    NSURLSessionDataTask *task = [self.manager POST:ZYZH_API(url) parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (fileType == 0) {// 图片
            //formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            for (int i = 0; i < filesArr.count; i++) {
                UIImage *image = filesArr[i];
                NSData *data = nil;
                if (maxByte > 0) {
                    data = [ZMSpeedy zm_getImgData:image toByte:maxByte];
                }else{
                    data = UIImageJPEGRepresentation(image,1);
                }
                NSString *fileName = [NSString stringWithFormat:@"%@_%d.png", str,i];
                [formData appendPartWithFileData:data name:@"files" fileName:fileName mimeType:@"image/jpeg"];
            }
        }
        if (fileType == 1) {/// 视频
            for (int i = 0; i < filesArr.count; i++) {
                NSString *videoUrl = filesArr[i];
                NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
                formatter.dateFormat=@"yyyyMMddHHmmss";
                NSString*str=[formatter stringFromDate:[NSDate date]];
                NSString*fileName=[NSString stringWithFormat:@"%@.mp4",str];
                NSData *fileData = [NSData dataWithContentsOfFile:videoUrl];
                [formData appendPartWithFileData:fileData name:@"files" fileName:fileName mimeType:@"application/octet-stream"];
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
             NSDictionary *dic = [ZMNetWorkingRequest jsonToDic:responseObject];
                       ZMLog(@"\n🌺🌺URL:\n%@\n🌸Response:\n%@",ZYZH_API(url),dic.mj_JSONString);
                       success(dic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            failure(error);
        }
    }];
    return task;
}

+ (NSDictionary *)jsonToDic:(NSData *)jsonData {
    NSError *error = nil;
    NSData *data = jsonData;
    NSDictionary *dicData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    if (error) {
        return @{};
    } else {
        return dicData;
    }
}

/// 设置请求头token
- (void)setTemporaryHeaderRequest {
    NSString *token = [UserInfoM getUserInfo].token;
    [self.manager.requestSerializer setValue:kIsEmptyStr(token)?@"":token forHTTPHeaderField:@"token"];
}


@end
